/**
 * Copyright 2006-2015 the original author or authors.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.mybatis.generator.codegen.mybatis3.javamapper;

import org.mybatis.generator.api.CommentGenerator;
import org.mybatis.generator.api.dom.java.CompilationUnit;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.api.dom.java.Interface;
import org.mybatis.generator.api.dom.java.JavaVisibility;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.api.dom.java.TopLevelClass;
import org.mybatis.generator.codegen.AbstractJavaClientGenerator;
import org.mybatis.generator.codegen.AbstractXmlGenerator;
import org.mybatis.generator.codegen.mybatis3.javamapper.elements.AbstractJavaMapperMethodGenerator;
import org.mybatis.generator.codegen.mybatis3.javamapper.elements.CountByExampleMethodGenerator;
import org.mybatis.generator.codegen.mybatis3.javamapper.elements.DeleteByExampleMethodGenerator;
import org.mybatis.generator.codegen.mybatis3.javamapper.elements.DeleteByPrimaryKeyMethodGenerator;
import org.mybatis.generator.codegen.mybatis3.javamapper.elements.InsertMethodGenerator;
import org.mybatis.generator.codegen.mybatis3.javamapper.elements.InsertSelectiveMethodGenerator;
import org.mybatis.generator.codegen.mybatis3.javamapper.elements.SelectByExampleWithBLOBsMethodGenerator;
import org.mybatis.generator.codegen.mybatis3.javamapper.elements.SelectByExampleWithoutBLOBsMethodGenerator;
import org.mybatis.generator.codegen.mybatis3.javamapper.elements.SelectByPrimaryKeyMethodGenerator;
import org.mybatis.generator.codegen.mybatis3.javamapper.elements.UpdateByExampleSelectiveMethodGenerator;
import org.mybatis.generator.codegen.mybatis3.javamapper.elements.UpdateByExampleWithBLOBsMethodGenerator;
import org.mybatis.generator.codegen.mybatis3.javamapper.elements.UpdateByExampleWithoutBLOBsMethodGenerator;
import org.mybatis.generator.codegen.mybatis3.javamapper.elements.UpdateByPrimaryKeySelectiveMethodGenerator;
import org.mybatis.generator.codegen.mybatis3.javamapper.elements.UpdateByPrimaryKeyWithBLOBsMethodGenerator;
import org.mybatis.generator.codegen.mybatis3.javamapper.elements.UpdateByPrimaryKeyWithoutBLOBsMethodGenerator;
import org.mybatis.generator.codegen.mybatis3.xmlmapper.XMLMapperGenerator;

import java.util.ArrayList;
import java.util.List;

import static org.mybatis.generator.internal.util.messages.Messages.getString;

/**
 * @author Jeff Butler
 */
public class JavaMapperGenerator extends AbstractJavaClientGenerator {

    /**
     *
     */
    public JavaMapperGenerator() {
        super(true);
    }

    public JavaMapperGenerator(boolean requiresMatchedXMLGenerator) {
        super(requiresMatchedXMLGenerator);
    }

    @Override
    public List<CompilationUnit> getCompilationUnits() {
        progressCallback.startTask(getString("Progress.17", //$NON-NLS-1$
                introspectedTable.getFullyQualifiedTable().toString()));
        CommentGenerator commentGenerator = context.getCommentGenerator();

        FullyQualifiedJavaType parameterType = introspectedTable.getRules().calculateAllFieldsClass();

        String pkClass;
        if (introspectedTable.getPrimaryKeyColumns().size() > 1) {
            pkClass = "java.lang.Object"; //$NON-NLS-1$
        } else {
            pkClass = introspectedTable.getPrimaryKeyColumns().get(0).getFullyQualifiedJavaType().toString();
        }
        FullyQualifiedJavaType pkClassType = new FullyQualifiedJavaType(pkClass);

        FullyQualifiedJavaType mapperAnnotation = new FullyQualifiedJavaType("org.apache.ibatis.annotations.Mapper");
        FullyQualifiedJavaType superInterface = new FullyQualifiedJavaType("org.tianyun.cloud.mybatis.mapper.BaseMapper");
        superInterface.addTypeArgument(pkClassType);
        superInterface.addTypeArgument(parameterType);

        FullyQualifiedJavaType type = new FullyQualifiedJavaType(introspectedTable.getMyBatis3JavaMapperType());
        Interface interfaze = new Interface(type);
        interfaze.addSuperInterface(superInterface);
        interfaze.setVisibility(JavaVisibility.PUBLIC);
        interfaze.addImportedType(parameterType);
        interfaze.addImportedType(superInterface);
        interfaze.addImportedType(mapperAnnotation);
        interfaze.addAnnotation("@Mapper");

        commentGenerator.addJavaFileComment(interfaze);

        // String rootInterface = introspectedTable.getTableConfigurationProperty(PropertyRegistry.ANY_ROOT_INTERFACE);
        // if (!stringHasValue(rootInterface)) {
        // rootInterface = context.getJavaClientGeneratorConfiguration().getProperty(PropertyRegistry.ANY_ROOT_INTERFACE);
        // }
        //
        // if (stringHasValue(rootInterface)) {
        // FullyQualifiedJavaType fqjt = new FullyQualifiedJavaType(rootInterface);
        // interfaze.addSuperInterface(fqjt);
        // interfaze.addImportedType(fqjt);
        // }
        // addCountByExampleMethod(interfaze);
        // addDeleteByExampleMethod(interfaze);
        // addDeleteByPrimaryKeyMethod(interfaze);
        // addInsertMethod(interfaze);
        // addInsertSelectiveMethod(interfaze);
        // addSelectByExampleWithBLOBsMethod(interfaze);
        // addSelectByExampleWithoutBLOBsMethod(interfaze);
        // addSelectByPrimaryKeyMethod(interfaze);
        // addUpdateByExampleSelectiveMethod(interfaze);
        // addUpdateByExampleWithBLOBsMethod(interfaze);
        // addUpdateByExampleWithoutBLOBsMethod(interfaze);
        // addUpdateByPrimaryKeySelectiveMethod(interfaze);
        // addUpdateByPrimaryKeyWithBLOBsMethod(interfaze);
        // addUpdateByPrimaryKeyWithoutBLOBsMethod(interfaze);

        List<CompilationUnit> answer = new ArrayList<CompilationUnit>();
        if (context.getPlugins().clientGenerated(interfaze, null, introspectedTable)) {
            answer.add(interfaze);
        }

        List<CompilationUnit> extraCompilationUnits = getExtraCompilationUnits();
        if (extraCompilationUnits != null) {
            answer.addAll(extraCompilationUnits);
        }

        addServiceClass(answer, commentGenerator, parameterType, type);

        return answer;
    }

    private void addServiceClass(List<CompilationUnit> answer, CommentGenerator commentGenerator, FullyQualifiedJavaType parameterType, FullyQualifiedJavaType mapperType) {
        String pakkage = introspectedTable.calculateJavaModelPackage();
        String serviceInterfaceName, serviceImplClassName;

        StringBuilder sb = new StringBuilder();
        sb.append(pakkage);
        sb.append(".service.");
        sb.append(introspectedTable.getFullyQualifiedTable().getDomainObjectName());
        sb.append("Service");
        serviceInterfaceName = sb.toString();

        sb.setLength(0);
        sb.append(pakkage);
        sb.append(".service.impl.");
        sb.append(introspectedTable.getFullyQualifiedTable().getDomainObjectName());
        sb.append("ServiceImpl");
        serviceImplClassName = sb.toString();

        String pkClass;
        if (introspectedTable.getPrimaryKeyColumns().size() > 1) {
            pkClass = "java.lang.Object"; //$NON-NLS-1$
        } else {
            pkClass = introspectedTable.getPrimaryKeyColumns().get(0).getFullyQualifiedJavaType().toString();
        }
        FullyQualifiedJavaType pkClassType = new FullyQualifiedJavaType(pkClass);
        FullyQualifiedJavaType superInterface = new FullyQualifiedJavaType("org.tianyun.cloud.mybatis.service.BaseService");
        superInterface.addTypeArgument(pkClassType);
        superInterface.addTypeArgument(parameterType);

        FullyQualifiedJavaType serviceInterfaceType = new FullyQualifiedJavaType(serviceInterfaceName);
        Interface serviceInterface = new Interface(serviceInterfaceType);
        serviceInterface.addSuperInterface(superInterface);
        serviceInterface.setVisibility(JavaVisibility.PUBLIC);
        serviceInterface.addImportedType(superInterface);
        serviceInterface.addImportedType(parameterType);
        serviceInterface.addImportedType(pkClassType);
        commentGenerator.addJavaFileComment(serviceInterface);
        answer.add(serviceInterface);

        FullyQualifiedJavaType serviceAnnotation = new FullyQualifiedJavaType("org.springframework.stereotype.Service");
        FullyQualifiedJavaType autowiredAnnotation = new FullyQualifiedJavaType("org.springframework.beans.factory.annotation.Autowired");
        FullyQualifiedJavaType serviceImplClassType = new FullyQualifiedJavaType(serviceImplClassName);

        TopLevelClass serviceImpl = new TopLevelClass(serviceImplClassType);
        serviceImpl.addSuperInterface(serviceInterfaceType);
        serviceImpl.setVisibility(JavaVisibility.PUBLIC);
        serviceImpl.addAnnotation("@Service");
        serviceImpl.addImportedType(serviceInterfaceType);
        serviceImpl.addImportedType(serviceAnnotation);
        serviceImpl.addImportedType(autowiredAnnotation);
        serviceImpl.addImportedType(mapperType);

        String mapperFieldName = String.valueOf(mapperType.getShortName().charAt(0)).toLowerCase() + mapperType.getShortName().substring(1);

        Field field = new Field(mapperFieldName, mapperType);
        field.setVisibility(JavaVisibility.PRIVATE);
        field.addAnnotation("@Autowired");
        serviceImpl.addField(field);

        Method method = new Method();
        method.setVisibility(JavaVisibility.PUBLIC);
        method.setReturnType(mapperType);
        method.setName("getBaseMapper");
        method.addBodyLine("return " + mapperFieldName + ";");
        method.addAnnotation("@SuppressWarnings(\"unchecked\")");
        method.addAnnotation("@Override");
        serviceImpl.addMethod(method);

        commentGenerator.addJavaFileComment(serviceImpl);
        answer.add(serviceImpl);
    }

    protected void addCountByExampleMethod(Interface interfaze) {
        if (introspectedTable.getRules().generateCountByExample()) {
            AbstractJavaMapperMethodGenerator methodGenerator = new CountByExampleMethodGenerator();
            initializeAndExecuteGenerator(methodGenerator, interfaze);
        }
    }

    protected void addDeleteByExampleMethod(Interface interfaze) {
        if (introspectedTable.getRules().generateDeleteByExample()) {
            AbstractJavaMapperMethodGenerator methodGenerator = new DeleteByExampleMethodGenerator();
            initializeAndExecuteGenerator(methodGenerator, interfaze);
        }
    }

    protected void addDeleteByPrimaryKeyMethod(Interface interfaze) {
        if (introspectedTable.getRules().generateDeleteByPrimaryKey()) {
            AbstractJavaMapperMethodGenerator methodGenerator = new DeleteByPrimaryKeyMethodGenerator(false);
            initializeAndExecuteGenerator(methodGenerator, interfaze);
        }
    }

    protected void addInsertMethod(Interface interfaze) {
        if (introspectedTable.getRules().generateInsert()) {
            AbstractJavaMapperMethodGenerator methodGenerator = new InsertMethodGenerator(false);
            initializeAndExecuteGenerator(methodGenerator, interfaze);
        }
    }

    protected void addInsertSelectiveMethod(Interface interfaze) {
        if (introspectedTable.getRules().generateInsertSelective()) {
            AbstractJavaMapperMethodGenerator methodGenerator = new InsertSelectiveMethodGenerator();
            initializeAndExecuteGenerator(methodGenerator, interfaze);
        }
    }

    protected void addSelectByExampleWithBLOBsMethod(Interface interfaze) {
        if (introspectedTable.getRules().generateSelectByExampleWithBLOBs()) {
            AbstractJavaMapperMethodGenerator methodGenerator = new SelectByExampleWithBLOBsMethodGenerator();
            initializeAndExecuteGenerator(methodGenerator, interfaze);
        }
    }

    protected void addSelectByExampleWithoutBLOBsMethod(Interface interfaze) {
        if (introspectedTable.getRules().generateSelectByExampleWithoutBLOBs()) {
            AbstractJavaMapperMethodGenerator methodGenerator = new SelectByExampleWithoutBLOBsMethodGenerator();
            initializeAndExecuteGenerator(methodGenerator, interfaze);
        }
    }

    protected void addSelectByPrimaryKeyMethod(Interface interfaze) {
        if (introspectedTable.getRules().generateSelectByPrimaryKey()) {
            AbstractJavaMapperMethodGenerator methodGenerator = new SelectByPrimaryKeyMethodGenerator(false);
            initializeAndExecuteGenerator(methodGenerator, interfaze);
        }
    }

    protected void addUpdateByExampleSelectiveMethod(Interface interfaze) {
        if (introspectedTable.getRules().generateUpdateByExampleSelective()) {
            AbstractJavaMapperMethodGenerator methodGenerator = new UpdateByExampleSelectiveMethodGenerator();
            initializeAndExecuteGenerator(methodGenerator, interfaze);
        }
    }

    protected void addUpdateByExampleWithBLOBsMethod(Interface interfaze) {
        if (introspectedTable.getRules().generateUpdateByExampleWithBLOBs()) {
            AbstractJavaMapperMethodGenerator methodGenerator = new UpdateByExampleWithBLOBsMethodGenerator();
            initializeAndExecuteGenerator(methodGenerator, interfaze);
        }
    }

    protected void addUpdateByExampleWithoutBLOBsMethod(Interface interfaze) {
        if (introspectedTable.getRules().generateUpdateByExampleWithoutBLOBs()) {
            AbstractJavaMapperMethodGenerator methodGenerator = new UpdateByExampleWithoutBLOBsMethodGenerator();
            initializeAndExecuteGenerator(methodGenerator, interfaze);
        }
    }

    protected void addUpdateByPrimaryKeySelectiveMethod(Interface interfaze) {
        if (introspectedTable.getRules().generateUpdateByPrimaryKeySelective()) {
            AbstractJavaMapperMethodGenerator methodGenerator = new UpdateByPrimaryKeySelectiveMethodGenerator();
            initializeAndExecuteGenerator(methodGenerator, interfaze);
        }
    }

    protected void addUpdateByPrimaryKeyWithBLOBsMethod(Interface interfaze) {
        if (introspectedTable.getRules().generateUpdateByPrimaryKeyWithBLOBs()) {
            AbstractJavaMapperMethodGenerator methodGenerator = new UpdateByPrimaryKeyWithBLOBsMethodGenerator();
            initializeAndExecuteGenerator(methodGenerator, interfaze);
        }
    }

    protected void addUpdateByPrimaryKeyWithoutBLOBsMethod(Interface interfaze) {
        if (introspectedTable.getRules().generateUpdateByPrimaryKeyWithoutBLOBs()) {
            AbstractJavaMapperMethodGenerator methodGenerator = new UpdateByPrimaryKeyWithoutBLOBsMethodGenerator();
            initializeAndExecuteGenerator(methodGenerator, interfaze);
        }
    }

    protected void initializeAndExecuteGenerator(AbstractJavaMapperMethodGenerator methodGenerator, Interface interfaze) {
        methodGenerator.setContext(context);
        methodGenerator.setIntrospectedTable(introspectedTable);
        methodGenerator.setProgressCallback(progressCallback);
        methodGenerator.setWarnings(warnings);
        methodGenerator.addInterfaceElements(interfaze);
    }

    public List<CompilationUnit> getExtraCompilationUnits() {
        return null;
    }

    @Override
    public AbstractXmlGenerator getMatchedXMLGenerator() {
        return new XMLMapperGenerator();
    }

}
